package com.alibaba.cirtus.ots.application.adapter.ability.facade.service.sap;

import com.alibaba.cirtus.ots.application.adapter.ability.model.enums.MnSAPStatus;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.ResponseUtil;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.citrus.ots.common.lock.RedisLock;
import com.alibaba.citrus.ots.common.util.IntegrateUtils;
import com.alibaba.citrus.ots.common.util.SapAndCrmFieldDealUtils;
import com.alibaba.cz.base.tool.DateFormatUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.middleware.cache.runtime.service.EpochCacheService;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.contants.BcOtsConstants;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByCodes2Request;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByCodes2Response;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationById2Request;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByIdsRequest;
import com.epoch.app.bcots.model.dto.OrganizationSDO;
import com.epoch.app.bcots.model.dto.SearchCargoZoneListRequest;
import com.epoch.app.bcots.model.dto.SearchCargoZoneListResponse;
import com.epoch.app.bcots.model.dto.WarehouseInfo;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.bcots.service.UnifiedInventoryService;
import com.epoch.app.otsapplicationadaptersdk.model.dto.MessageHeaderSDO;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SapRetrySaveRequest;
import com.epoch.app.otsapplicationadaptersdk.model.enums.RetryStatus;
import com.epoch.app.otsapplicationadaptersdk.model.enums.SapApiCode;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapCommDetail;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapCommResponse;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapCommSDO;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf007Request;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf007SDO;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf007detail;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf008Request;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf008SDO;
import com.epoch.app.otsapplicationadaptersdk.sap.mnsapif007.model.MnSapIf007;
import com.epoch.app.otsapplicationadaptersdk.sap.mnsapif007.service.MnSapIf007Service;
import com.epoch.app.otsapplicationadaptersdk.sapretrywrite.service.SapRetryWriteService;
import com.epoch.app.otsplatformenhance.interfacedatasyncconfigquery.service.InterfaceDataSyncConfigQueryService;
import com.epoch.app.otsplatformenhance.model.dto.BatchQueryAddress2Request;
import com.epoch.app.otsplatformenhance.model.dto.BatchQueryAddress2Response;
import com.epoch.app.otsplatformenhance.model.dto.DataCheckRequest;
import com.epoch.app.otsplatformenhance.model.dto.GetOrganiztionByIdRequest;
import com.epoch.app.otsplatformenhance.model.enums.OrderTypeEnum;
import com.epoch.app.otsplatformenhance.sdo.CustomerAddressSDO;
import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
import com.epoch.app.otsunifiedinventory.api.allocateapplyorderread.dto.GetAllocateApplyOrderIdByOutAllocateApplyOrderIdRequest;
import com.epoch.app.otsunifiedinventory.api.allocateapplyorderread.service.AllocateApplyOrderReadService;
import com.epoch.app.otsunifiedinventory.api.allocateapplyorderwrite.service.AllocateApplyOrderWriteService;
import com.epoch.app.otsunifiedinventory.api.forecastwarehouse.dto.QueryWarehouseByFactoryCodeAndWarehouseCodeRequest;
import com.epoch.app.otsunifiedinventory.api.forecastwarehouse.service.ForecastWarehouseService;
import com.epoch.app.otsunifiedinventory.dto.request.QueryAllocateApplyOrderRequest;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateApplyOrderDetailDTO;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderDetailCreateDTO;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderUpdateDTO;
import com.epoch.app.otsunifiedinventory.model.dto.WarehouseInfoDTO;
import com.epoch.app.otsunifiedinventory.sdo.enums.DocumentTypeEnum;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class MnSapIf007ServiceImpl implements MnSapIf007Service {
    @Autowired
    private UnifiedInventoryService unifiedInventoryService;
    @Resource
    ForecastWarehouseService forecastWarehouseService;
    @Resource
    AllocateApplyOrderWriteService allocateApplyOrderWriteService;

    @Resource
    AllocateApplyOrderReadService allocateApplyOrderReadService;

    @Resource
    OtsPlatformEnhanceService otsPlatformEnhanceService;
    @Autowired
    private InterfaceDataSyncConfigQueryService interfaceDataSyncConfigQueryService;

    @Resource
    BaseDataService baseDataService;
    @Resource
    SapRetryWriteService sapRetryWriteService;
    @Resource
    EpochCacheService epochCacheService;
    private static final String FORECAST_ORDER_CACHE_KEY = "FORECAST_ORDER_CACHE_KEY_";
    //设置sap过期时间为
    private static final Long SAP_TIMESTAMP_CACHE_EXPIRE = 60 * 60 * 24 * 100L;
    @Value("${ots.checkTimestamp:0}")
    private boolean checkTimestamp;
    private static com.alibaba.cz.base.tool.log.Log log = com.alibaba.cz.base.tool.log.Log.getLogger(MnSapIf013ServiceImpl.class);

    @ProcessInvoker(remark = "MnSapIf007Service", errorCode = "SAP更新调拨预报单到订单共享平台", printLog = true)
    @Override
    public MnSapCommResponse externalSyncUpdateForecast(MnSapIf007Request mnSapIf007Request) {
        MnSapCommResponse mnSapCommResponse = new MnSapCommResponse();
        //1.获取入参值
        MnSapIf007SDO mnSapIf007SDO = mnSapIf007Request.getData();
        try (RedisLock lock = new RedisLock(BcOtsConstants.REDIS_CACHE_CODE(),"allocateApplyOrderUpdate_" + mnSapIf007SDO.getHeaderKey(),5 * 60 * 1000,10 * 60 * 1000)){
            if (!lock.lock()) {
                MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                mnSapCommSDO.setMessage("获取分布式锁失败");
                mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                saveSapRetry(mnSapIf007Request,"获取分布式锁失败");
                return success(mnSapIf007Request);
            }
            if (Objects.isNull(mnSapIf007SDO)){
                mnSapIf007SDO = IntegrateUtils.safeGetMessageData(MnSapIf007SDO.class);
            }
            MessageHeaderSDO messageHeader = mnSapIf007Request.getMessageHeader();
            if (Objects.isNull(messageHeader)){
                messageHeader = IntegrateUtils.safeGetMessageHeader(MessageHeaderSDO.class);
            }
            if (Objects.nonNull(messageHeader)){
                mnSapCommResponse.setInterfacePath(messageHeader.getInterfacePath());
                mnSapCommResponse.setMessageId(messageHeader.getMessageId());
            }
            //校验调拨预报单是否为空
            if (Objects.isNull(mnSapIf007SDO)){
                MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                mnSapCommSDO.setMessage("调拨预报单信息不能为空");
                mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                saveSapRetry(mnSapIf007Request,"调拨预报单信息不能为空");
                return mnSapCommResponse;
            }
            //校验预报单明细货品是否为空
            if (CollectionUtils.isEmpty(mnSapIf007SDO.getItems())){
                MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                mnSapCommSDO.setMessage("调拨预报单明细信息不能为空");
                mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                saveSapRetry(mnSapIf007Request,"调拨预报单明细信息不能为空");
                return mnSapCommResponse;
            }
            //处理送达方和售达方前置0
            mnSapIf007SDO.setDeliveryPartCode(SapAndCrmFieldDealUtils.generateIdField(mnSapIf007SDO.getDeliveryPartCode()));
            mnSapIf007SDO.setSoldPartCode(SapAndCrmFieldDealUtils.generateIdField(mnSapIf007SDO.getSoldPartCode()));
            //获取明细
            List<MnSapIf007detail> mnSapIf007details = mnSapIf007SDO.getItems();
            //校验明细是否重复
            HashSet mnSapIf007detailSet = new HashSet();
            for (MnSapIf007detail mnSapIf007detail:mnSapIf007details){
                mnSapIf007detailSet.add(mnSapIf007detail.getScItemId());
            }
            if (mnSapIf007details.size()!=mnSapIf007detailSet.size()){
                MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                mnSapCommSDO.setMessage("调拨预报单明细货品编码不能重复");
                mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                saveSapRetry(mnSapIf007Request,"调拨预报单明细货品编码不能重复");
                return mnSapCommResponse;
            }
            /**
             * 如果预报单号和外部行号为空走新增逻辑，如果有外部预报单号没预报单号，根据外部预报单号找预报单号 找到了走新增
             * sapChannel: 90：计划调拨  20：总部销售调拨 （判断是否直发客户（参照售达方、送达方备注）
             * 判断是否工厂直发客户：
             * 1、查收货仓的售达方、送达方编码（对应售达方、送达方不唯一或查不到报错提示）--非直发客户
             *  2、查不到在根据售达方（soldPartCode）和送达方（deliveryPartCode）先找直发客户（对应客户编码、客户地址编码）如果对应上则是直发客户
             *
             * 补充：1、提报组织根据收货仓或客户的销售组织带出
             * 2、分公司客户暂不处理
             */
            boolean isAddAllocateApplyOrder = false;
            if (StringUtils.isEmpty(mnSapIf007SDO.getAllocateApplyOrderId())&&StringUtils.isEmpty(mnSapIf007SDO.getOutAllocateApplyOrderId())){
                isAddAllocateApplyOrder = true;
            }else{
                //如果预报单号为空，外部预报单号有值，去库中根据外部预报单号找预报单号，找不到走新增
                if (StringUtils.isEmpty(mnSapIf007SDO.getAllocateApplyOrderId())&&StringUtils.isNotEmpty(mnSapIf007SDO.getOutAllocateApplyOrderId())){
                    GetAllocateApplyOrderIdByOutAllocateApplyOrderIdRequest request = new GetAllocateApplyOrderIdByOutAllocateApplyOrderIdRequest();
                    request.setOutAllocateApplyOrderId(mnSapIf007SDO.getOutAllocateApplyOrderId());
                    Result<String> result = allocateApplyOrderReadService.getAllocateApplyOrderIdByOutAllocateApplyOrderId(request);
                    if (Objects.nonNull(result)&&StringUtils.isNotEmpty(result.getResult())){
                        mnSapIf007SDO.setAllocateApplyOrderId(result.getResult());
                    }else{
                        isAddAllocateApplyOrder = true;
                    }
                }
            }
            //判断创建什么类型的调拨预报单
            String type = DocumentTypeEnum.PLANNED_ALLOCATION.getCode();
            if ("20".equals(mnSapIf007SDO.getSapChannel())) {
                type = DocumentTypeEnum.HEADQUARTERS_SALES_ALLOCATION.getCode();
            }

            //如果需要校验时间戳
            if (checkTimestamp){
                //时间戳格式校验
                String check = ResponseUtil.check(mnSapIf007SDO.getFeatures());
                if (StringUtils.isNotBlank(check)){
//                saveSapRetry(mnSapIf007Request,check);
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage(check);
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    return mnSapCommResponse;
                }
                //时间戳的判断放在这里 2022.05.24 接口时间戳
                boolean checkModifierTime = checkModifierTime(mnSapIf007SDO);
                //时间校验不通过 放入重试表
                if (!checkModifierTime ){
                    saveSapRetry(mnSapIf007Request,"当前修改时间早于上一次 不允许更新");
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("当前修改时间早于上一次 不允许更新");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"当前修改时间早于上一次 不允许更新");
                    return mnSapCommResponse;
                }else {
                    //校验通过就要放入时间戳
//                    cache(mnSapIf007SDO.getOutAllocateApplyOrderId(),mnSapIf007SDO.getFeatures());
                }
            }
            if (isAddAllocateApplyOrder) {

                //是否工厂直发
                Boolean isDTC =false;
                //提报组织
                String applyOrgId = "";
                String freshApplyOrgId = null;
                //提报组织外部编码 用于工厂直发场景
                String orgOutCode = "";
                //地址编码
                String address = "";
                //收货仓库
                String warehouseId = "";
                if (StringUtils.isEmpty(mnSapIf007SDO.getSapChannel())) {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("分销渠道字段不能为空");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"分销渠道字段不能为空");
                    return mnSapCommResponse;
                }
                if (StringUtils.isEmpty(mnSapIf007SDO.getSoldPartCode())) {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("售达方不能为空");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"售达方不能为空");
                    return mnSapCommResponse;
                }
                if (StringUtils.isEmpty(mnSapIf007SDO.getDeliveryPartCode())) {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("送达方不能为空");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"送达方不能为空");
                    return mnSapCommResponse;
                }
                //类型是90 走计划调拨逻辑 使用总部售达方和总部送达方找仓库，如果是20走销售调拨，先查找地址信息，查不到根据售达方和送达方找仓库信息
                if (DocumentTypeEnum.HEADQUARTERS_SALES_ALLOCATION.getCode().equals(type)){

                    //根据售达方和送达方查找仓库信息，查出多个返回错误，如果有值 取销售组织
                    SearchCargoZoneListRequest searchCargoZoneListRequest = new SearchCargoZoneListRequest();
                    searchCargoZoneListRequest.setSapSaleBPCode(mnSapIf007SDO.getSoldPartCode());
                    //送达方
                    searchCargoZoneListRequest.setSapDeliveryBPCode(mnSapIf007SDO.getDeliveryPartCode());
                    log.info("根据售达方和送达方查找仓库信息入参：售达方："+mnSapIf007SDO.getSoldPartCode()+",送达方："+mnSapIf007SDO.getDeliveryPartCode());
                    SearchCargoZoneListResponse searchCargoZoneListResponse = unifiedInventoryService.searchCargoZoneList(searchCargoZoneListRequest);
                    log.info("根据总部售达方和总部送达方查找仓库信息出参："+ JSONObject.toJSONString(searchCargoZoneListResponse));
                    if (Objects.nonNull(searchCargoZoneListResponse)&&CollectionUtils.isNotEmpty(searchCargoZoneListResponse.getResult())&&searchCargoZoneListResponse.getResult().size()==1) {
                        WarehouseInfo warehouseInfo = searchCargoZoneListResponse.getResult().get(0);
                        warehouseId = warehouseInfo.getId();
                        applyOrgId = warehouseInfo.getSaleOrgId();
                        OrganizationSDO orgSDO = getOrgSDO(applyOrgId);
                        //收货逻辑仓库-》销售组织-〉所属公司
                        if (orgSDO != null && StringUtils.isNotBlank(orgSDO.getParentId())){
                            freshApplyOrgId = orgSDO.getParentId();
                        }

                    } else {
                        if (Objects.nonNull(searchCargoZoneListResponse)&&CollectionUtils.isNotEmpty(searchCargoZoneListResponse.getResult())&&searchCargoZoneListResponse.getResult().size()>1) {
                            MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                            mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                            mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                            mnSapCommSDO.setMessage("售达方或送达方有误，请重新填写");
                            mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                            saveSapRetry(mnSapIf007Request,"售达方或送达方有误，请重新填写");
                            return mnSapCommResponse;
                        }else{
                            //查找客户和客户地址编码
                            BatchQueryAddress2Request batchQueryAddress2Request = new BatchQueryAddress2Request();
                            batchQueryAddress2Request.setAddressCodes(Lists.newArrayList(mnSapIf007SDO.getDeliveryPartCode()));
                            log.info("根据送达方查找客户地址信息入参：送达方："+mnSapIf007SDO.getDeliveryPartCode());
                            BatchQueryAddress2Response batchQueryAddress2Response = otsPlatformEnhanceService.batchQueryAddress2(batchQueryAddress2Request);
                            log.info("根据送达方查找客户地址信息出参："+ JSONObject.toJSONString(batchQueryAddress2Response));
                            if (Objects.nonNull(batchQueryAddress2Response) && CollectionUtils.isNotEmpty(batchQueryAddress2Response.getResult())) {
                                isDTC = true;
                                //根据报文里的soldPartCode 获取到组织架构里的组织id 这个值和组织编号相同
                                orgOutCode = getOrgOutCodeBySoldPartCode(mnSapIf007SDO.getSoldPartCode());
                                address = batchQueryAddress2Response.getResult().get(0).getId();
                                //收货逻辑仓库-》销售组织-〉所属公司
                                if (CollectionUtils.isNotEmpty(batchQueryAddress2Response.getResult())){
                                    CustomerAddressSDO customerAddressSDO = batchQueryAddress2Response.getResult().get(0);
                                    if (customerAddressSDO != null){
                                        String orgBussinessUnitCode = customerAddressSDO.getOrgBussinessUnitCode();
                                        if (StringUtils.isNotBlank(orgBussinessUnitCode)){
                                            freshApplyOrgId = orgBussinessUnitCode;
                                        }
                                    }
                                }
                                //根据报文里的soldPartCode 获取到组织架构里的组织id 这个值和组织编号相同 ,工厂直发的优先取这个值
                                if (StringUtils.isNotBlank(orgOutCode)){
                                    freshApplyOrgId = orgOutCode;
//                                getOrgSDO(orgOutCode)
                                }
                            } else {
                                MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                                mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                                mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                                mnSapCommSDO.setMessage("售达方或送达方有误，请重新填写");
                                mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                                saveSapRetry(mnSapIf007Request,"售达方或送达方有误，请重新填写");
                                return mnSapCommResponse;
                            }
                        }
                    }
                }else{
                    //根据总部售达方和总部送达方查找仓库信息，查出多个或一个都没查到 返回错误，如果有值 取销售组织
                    SearchCargoZoneListRequest searchCargoZoneListRequest = new SearchCargoZoneListRequest();
                    searchCargoZoneListRequest.setSapInternalSalesBPCode(mnSapIf007SDO.getSoldPartCode());
                    //总部送达方
                    searchCargoZoneListRequest.setSapInternalDeliveryBPCode(mnSapIf007SDO.getDeliveryPartCode());
                    log.info("根据总部售达方和总部送达方查找仓库信息入参：总部售达方："+mnSapIf007SDO.getSoldPartCode()+",总部送达方："+mnSapIf007SDO.getDeliveryPartCode());
                    SearchCargoZoneListResponse searchCargoZoneListResponse = unifiedInventoryService.searchCargoZoneList(searchCargoZoneListRequest);
                    log.info("根据总部售达方和总部送达方查找仓库信息出参："+ JSONObject.toJSONString(searchCargoZoneListResponse));
                    if (Objects.nonNull(searchCargoZoneListResponse)&&CollectionUtils.isNotEmpty(searchCargoZoneListResponse.getResult())&&searchCargoZoneListResponse.getResult().size()==1) {
                        WarehouseInfo warehouseInfo = searchCargoZoneListResponse.getResult().get(0);
                        warehouseId = warehouseInfo.getId();
                        orgOutCode = getOrgOutCodeBySoldPartCode(mnSapIf007SDO.getSoldPartCode());
                        OrganizationSDO orgSDO = getOrgSDO(warehouseInfo.getSaleOrgId());
                        //收货逻辑仓库-》销售组织-〉所属公司
                        if (orgSDO != null && StringUtils.isNotBlank(orgSDO.getParentId())){
                            freshApplyOrgId = orgSDO.getParentId();
                        }
                    } else {
                        MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                        mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                        mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                        mnSapCommSDO.setMessage("售达方或送达方有误，请重新填写");
                        mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                        saveSapRetry(mnSapIf007Request,"售达方或送达方有误，请重新填写");
                        return mnSapCommResponse;
                    }
                }

                try {
                    //根据配置表进行数据拦截过滤
                    DataCheckRequest dataCheckRequest = new DataCheckRequest();
                    dataCheckRequest.setOrderType(OrderTypeEnum.APPLYALLOCATE.getCode());
                    dataCheckRequest.setOrgOutCode(getOrgCode(applyOrgId));
                    dataCheckRequest.setVariable(SapAndCrmFieldDealUtils.toDateString(mnSapIf007SDO.getOuterCreateDate()));
                    Result<Boolean> checkResult = interfaceDataSyncConfigQueryService.dataCheck(dataCheckRequest);
                    if (checkResult != null && checkResult.getResult() != null && !checkResult.getResult()){
                        log.info("007.interfaceDataSyncConfigQueryService 拦截 "+JSONObject.toJSONString(mnSapIf007SDO));
                        MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                        mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                        mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
                        mnSapCommSDO.setMessage("成功！");
                        mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                        return success(mnSapIf007Request);
                    }
                } catch (Throwable e) {
                    log.error("007.interfaceDataSyncConfigQueryService.Error", e);
                }

                //开始组装保存预报单主单数据和明细数据
                AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
                //调拨预报单类型
                allocateApplyOrderUpdateDTO.setType(type);
                //是否工厂直发
                allocateApplyOrderUpdateDTO.setIsDTC(isDTC);
                //提报组织
                if (StringUtils.isNotBlank(freshApplyOrgId)){
                    allocateApplyOrderUpdateDTO.setApplyOrgId(freshApplyOrgId);
                }else{
                    allocateApplyOrderUpdateDTO.setApplyOrgId(StringUtils.isNotBlank(orgOutCode)?orgOutCode:applyOrgId);
                }
                //外部单据号
                allocateApplyOrderUpdateDTO.setOutAllocateApplyOrderId(mnSapIf007SDO.getOutAllocateApplyOrderId());
                //销售组织code
                allocateApplyOrderUpdateDTO.setSaleOrganizationCode(mnSapIf007SDO.getSaleOrganizationCode());
                //部门（产品组）
                allocateApplyOrderUpdateDTO.setGoodsGroup(mnSapIf007SDO.getProductGroupCode());
                //单据日期
                allocateApplyOrderUpdateDTO.setOrderTime(DateFormatUtil.parse(mnSapIf007SDO.getDocTime()));
                //有效起始时间
                allocateApplyOrderUpdateDTO.setTakeEffectTime(DateFormatUtil.parse(mnSapIf007SDO.getBeginTime()));
                //报价有效至
                allocateApplyOrderUpdateDTO.setInvalidDate(DateFormatUtil.parse(mnSapIf007SDO.getEndTime()));
                // 预计交货时间
                allocateApplyOrderUpdateDTO.setHopeDeliveryTime(DateFormatUtil.parse(mnSapIf007SDO.getExpectedDeliveryTime()));
                //客户地址
                if (StringUtils.isNotEmpty(address)) {
                    allocateApplyOrderUpdateDTO.setCustomerAddress(address);
                }
                //总部内部送达方编号 收货仓带出
                allocateApplyOrderUpdateDTO.setSapInternalDeliveryBPCode(mnSapIf007SDO.getDeliveryPartCode());
                //总部内部售达方编号 收货仓带出
                allocateApplyOrderUpdateDTO.setSapInternalSalesBPCode(mnSapIf007SDO.getSoldPartCode());
                //总部渠道编码
                allocateApplyOrderUpdateDTO.setHeadquartersChannelCode(mnSapIf007SDO.getSapChannel());
                //总部组织编码 默认6000
                allocateApplyOrderUpdateDTO.setHeadquartersOrganizationCode("6000");

                //如果没有工厂和库存code 就不找收货单
                if (Objects.nonNull(mnSapIf007SDO.getDeliveryFactoryCode())) {
                    //收货id 根据工厂和库存code查找
                    QueryWarehouseByFactoryCodeAndWarehouseCodeRequest queryWarehouseByFactoryCodeAndWarehouseCodeRequest = new QueryWarehouseByFactoryCodeAndWarehouseCodeRequest();
                    queryWarehouseByFactoryCodeAndWarehouseCodeRequest.setWarehouseCode(mnSapIf007SDO.getDeliveryInventoryLocation());
                    queryWarehouseByFactoryCodeAndWarehouseCodeRequest.setFactoryCode(mnSapIf007SDO.getDeliveryFactoryCode());
                    Result<List<WarehouseInfoDTO>> listResult = forecastWarehouseService.queryWarehouseByFactoryCodeAndWarehouseCode(queryWarehouseByFactoryCodeAndWarehouseCodeRequest);
                    //发货仓库
                    if (Objects.nonNull(listResult)&&CollectionUtils.isNotEmpty(listResult.getResult())){
                        allocateApplyOrderUpdateDTO.setShipWarehouseId(listResult.getResult().get(0).getId());
                    }
                } else {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("工厂code不能为空！");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"工厂code不能为空！");
                    return mnSapCommResponse;
                }
                //收货仓库
                if (StringUtils.isNotEmpty(warehouseId)){
                    allocateApplyOrderUpdateDTO.setReceiveWarehouseId(Integer.valueOf(warehouseId));
                }
                //装运条件  获取为空
                allocateApplyOrderUpdateDTO.setShipMethod(mnSapIf007SDO.getShipType());
                //备注
                allocateApplyOrderUpdateDTO.setRemark(mnSapIf007SDO.getRemark());
                //明细deliveryInventoryLocation
                List<AllocateApplyOrderDetailCreateDTO> allocateApplyOrderDetails = new ArrayList<>();
                for (MnSapIf007detail mnSapIf007detail : mnSapIf007details) {
                    AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO = new AllocateApplyOrderDetailCreateDTO();
                    //sap行号
                    allocateApplyOrderDetailCreateDTO.setOutLineNo(mnSapIf007detail.getOutAllocateApplyOrderLineId());
                    //物料编号/货品编码
                    if (Objects.nonNull(mnSapIf007detail.getScItemId())) {
                        String s = mnSapIf007detail.getScItemId();
                        if (s.length()>12){
                            s = s.substring(s.length()-12);
                        }
                        allocateApplyOrderDetailCreateDTO.setScItemId(s);
                    }
                    //数量
                    allocateApplyOrderDetailCreateDTO.setApplyQuantity(Double.valueOf(mnSapIf007detail.getQuantity()).intValue());
                    //销售单位
                    allocateApplyOrderDetailCreateDTO.setUom(mnSapIf007detail.getUnit());
                    //单价
                    if (Objects.nonNull(mnSapIf007detail.getPrice())) {
                        allocateApplyOrderDetailCreateDTO.setUnitPrice(new BigDecimal(mnSapIf007detail.getPrice()));
                    }
                    //折扣后总金额
                    if (Objects.nonNull(mnSapIf007detail.getSubTotalAmount())) {
                        allocateApplyOrderDetailCreateDTO.setSubtotalMoney(new BigDecimal(mnSapIf007detail.getSubTotalAmount()));
                    }
                    //拒绝原因编码
                    allocateApplyOrderDetailCreateDTO.setCloseCode(StringUtils.isNotBlank(mnSapIf007detail.getCloseCode())?mnSapIf007detail.getCloseCode() :mnSapIf007detail.getExt());
                    //拒绝原因描述
                    allocateApplyOrderDetailCreateDTO.setCloseReason(StringUtils.isNotBlank(mnSapIf007detail.getCloseReason())?mnSapIf007detail.getCloseReason():mnSapIf007detail.getExt1());
                    allocateApplyOrderDetailCreateDTO.setIsClosed(!org.apache.commons.lang3.StringUtils.isAllBlank(mnSapIf007detail.getExt1(),mnSapIf007detail.getCloseReason()) ? 1 : 0);
//                    allocateApplyOrderDetailCreateDTO.setIsClosed(Objects.nonNull(mnSapIf007detail.getCloseReason()) ? 1 : 0);
                    //行备注
                    allocateApplyOrderDetailCreateDTO.setRemark(mnSapIf007detail.getRemarks());
                    allocateApplyOrderDetails.add(allocateApplyOrderDetailCreateDTO);
                }

                allocateApplyOrderUpdateDTO.setList(allocateApplyOrderDetails);
                Result<String> result = allocateApplyOrderWriteService.sapCreateAllocateApplyOrder(allocateApplyOrderUpdateDTO);
                if (Objects.isNull(result)||StringUtils.isEmpty(result.getResult())){
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("调拨预报单创建失败！");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"调拨预报单创建失败！");
                    return mnSapCommResponse;
                }
                mnSapIf007SDO.setAllocateApplyOrderId(result.getResult());
            } else {
                //查找预调拨单数据
                QueryAllocateApplyOrderRequest request = new QueryAllocateApplyOrderRequest();
                request.setCode(mnSapIf007SDO.getAllocateApplyOrderId());
                Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(request);
                if (Objects.isNull(allocateApplyOrderDetailDTOResult) || Objects.isNull(allocateApplyOrderDetailDTOResult.getResult())) {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("预报单号查不到数据");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"预报单号查不到数据");
                    return mnSapCommResponse;
                }
                AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO = allocateApplyOrderDetailDTOResult.getResult();
                //类型不一致不准修改
                if (!type.equals(allocateApplyOrderDetailDTO.getType())){
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("修改调拨预报单时不能修改调拨预报单类型！");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"修改调拨预报单时不能修改调拨预报单类型！");
                    return mnSapCommResponse;
                }

                AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
                allocateApplyOrderUpdateDTO.setId(allocateApplyOrderDetailDTO.getId());
                //预报单号
                allocateApplyOrderUpdateDTO.setCode(mnSapIf007SDO.getAllocateApplyOrderId());
                //外部单据号
                allocateApplyOrderUpdateDTO.setOutAllocateApplyOrderId(mnSapIf007SDO.getOutAllocateApplyOrderId());
                //报价单类型 平台无这字段
//        销售组织code
//        allocateApplyOrderUpdateDTO.setSaleOrganizationCode(mnSapIf007SDO.getSaleOrganizationCode());
//        //分销渠道
//        allocateApplyOrderUpdateDTO.setHeadquartersChannelCode(mnSapIf007SDO.getSapChannel());
//        //部门（产品组）
//        allocateApplyOrderUpdateDTO.setGoodsGroup(mnSapIf007SDO.getProductGroupCode());
//        //销售办公室 销售渠道
//        allocateApplyOrderUpdateDTO.setSaleChannel(mnSapIf007SDO.getSapChannel());
//        //销售部门code
//        allocateApplyOrderUpdateDTO.setSaleDepartmentCode(mnSapIf007SDO.getSaleDepartmentCode());
//        //更改人mnSapIf007SDO.getModifier()
//        allocateApplyOrderUpdateDTO.setUpdater("1234");
//        //更改日期mnSapIf007SDO.getModifyTime()
//        allocateApplyOrderUpdateDTO.setGmtModified(new Date());
//        //单据日期
                allocateApplyOrderUpdateDTO.setOrderTime(DateFormatUtil.parse(mnSapIf007SDO.getDocTime()));
                //有效起始时间
                allocateApplyOrderUpdateDTO.setTakeEffectTime(DateFormatUtil.parse(mnSapIf007SDO.getBeginTime()));
                //报价有效至
                allocateApplyOrderUpdateDTO.setInvalidDate(DateFormatUtil.parse(mnSapIf007SDO.getEndTime()));
                // 预计交货时间
                allocateApplyOrderUpdateDTO.setHopeDeliveryTime(DateFormatUtil.parse(mnSapIf007SDO.getExpectedDeliveryTime()));
                //如果没有工厂和库存code 就不找收货单
//        if (Objects.nonNull(mnSapIf007SDO.getDeliveryInventoryLocation())&&Objects.nonNull(mnSapIf007SDO.getDeliveryFactoryCode())){

                //提报组织
                String applyOrgId = "";
                if (Objects.nonNull(mnSapIf007SDO.getDeliveryFactoryCode())) {
                    //收货id 根据工厂和库存code查找
                    QueryWarehouseByFactoryCodeAndWarehouseCodeRequest queryWarehouseByFactoryCodeAndWarehouseCodeRequest = new QueryWarehouseByFactoryCodeAndWarehouseCodeRequest();
                    queryWarehouseByFactoryCodeAndWarehouseCodeRequest.setWarehouseCode(mnSapIf007SDO.getDeliveryInventoryLocation());
                    queryWarehouseByFactoryCodeAndWarehouseCodeRequest.setFactoryCode(mnSapIf007SDO.getDeliveryFactoryCode());
                    Result<List<WarehouseInfoDTO>> listResult = forecastWarehouseService.queryWarehouseByFactoryCodeAndWarehouseCode(queryWarehouseByFactoryCodeAndWarehouseCodeRequest);
                    //发货仓库
                    if (Objects.nonNull(listResult)&&CollectionUtils.isNotEmpty(listResult.getResult())){
                        allocateApplyOrderUpdateDTO.setShipWarehouseId(listResult.getResult().get(0).getId());
                        applyOrgId = listResult.getResult().get(0).getSaleOrgId();
                    }
                }

                try {
                    //根据配置表进行数据拦截过滤
                    DataCheckRequest dataCheckRequest = new DataCheckRequest();
                    dataCheckRequest.setOrderType(OrderTypeEnum.APPLYALLOCATE.getCode());
                    dataCheckRequest.setOrgOutCode(getOrgCode(applyOrgId));
                    dataCheckRequest.setVariable(SapAndCrmFieldDealUtils.toDateString(mnSapIf007SDO.getOuterCreateDate()));
                    Result<Boolean> checkResult = interfaceDataSyncConfigQueryService.dataCheck(dataCheckRequest);
                    if (checkResult != null && checkResult.getResult() != null && !checkResult.getResult()){
                        log.info("007.interfaceDataSyncConfigQueryService 拦截 "+JSONObject.toJSONString(mnSapIf007SDO));
                        MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                        mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                        mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
                        mnSapCommSDO.setMessage("成功！");
                        mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                        return success(mnSapIf007Request);
                    }
                } catch (Throwable e) {
                    log.error("007.interfaceDataSyncConfigQueryService.Error", e);
                }

                //装运条件  获取为空
                allocateApplyOrderUpdateDTO.setShipMethod(mnSapIf007SDO.getShipType());
                //备注
                allocateApplyOrderUpdateDTO.setRemark(mnSapIf007SDO.getRemark());
                //售达方
//        allocateApplyOrderUpdateDTO.setSapSalesBPCode(mnSapIf007SDO.getSoldPartCode());
//        //送达方
//        allocateApplyOrderUpdateDTO.setSapDeliveryBPCode(mnSapIf007SDO.getDeliveryPartCode());
                //扩展信息
//        allocateApplyOrderUpdateDTO.set(null,mnSapIf007SDO.getFeatures());
                //文档中没这个字段
//        allocateApplyOrderUpdateDTO.set(null,mnSapIf007SDO.getExt());
                //明细deliveryInventoryLocation
                List<AllocateApplyOrderDetailCreateDTO> allocateApplyOrderDetails = new ArrayList<>();
                for (MnSapIf007detail mnSapIf007detail : mnSapIf007details) {
                    AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO = new AllocateApplyOrderDetailCreateDTO();
                    //预调拨单id
                    allocateApplyOrderDetailCreateDTO.setAllocateApplyOrderId(Integer.valueOf(allocateApplyOrderDetailDTO.getId().toString()));
//            //行号
//            if (Objects.isNull(mnSapIf007detail.getAllocateApplyOrderLineId())){
//                allocateApplyOrderDetailCreateDTO.setLineNo(Integer.valueOf(mnSapIf007detail.getAllocateApplyOrderLineId()));
//            }
//            //sap行号
                    allocateApplyOrderDetailCreateDTO.setOutLineNo(mnSapIf007detail.getOutAllocateApplyOrderLineId());
//            //物料编号/货品编码
                    if (Objects.nonNull(mnSapIf007detail.getScItemId())) {
                        String s = mnSapIf007detail.getScItemId();
                        if (s.length()>12){
                            s = s.substring(s.length()-12);
                        }
                        allocateApplyOrderDetailCreateDTO.setScItemId(s);
                    }
//            //数量
                    allocateApplyOrderDetailCreateDTO.setApplyQuantity(Double.valueOf(mnSapIf007detail.getQuantity()).intValue());
//            //销售单位
                    allocateApplyOrderDetailCreateDTO.setUom(mnSapIf007detail.getUnit());
//            //单价
                    if (Objects.nonNull(mnSapIf007detail.getPrice())) {
                        allocateApplyOrderDetailCreateDTO.setUnitPrice(new BigDecimal(mnSapIf007detail.getPrice()));
                    }
//            //折扣后总金额
                    if (Objects.nonNull(mnSapIf007detail.getSubTotalAmount())) {
                        allocateApplyOrderDetailCreateDTO.setSubtotalMoney(new BigDecimal(mnSapIf007detail.getSubTotalAmount()));
                    }
//            //拒绝原因编码
                    allocateApplyOrderDetailCreateDTO.setCloseCode(StringUtils.isNotBlank(mnSapIf007detail.getCloseCode())?mnSapIf007detail.getCloseCode():mnSapIf007detail.getExt());
//            //拒绝原因描述
                    allocateApplyOrderDetailCreateDTO.setCloseReason(StringUtils.isNotBlank(mnSapIf007detail.getCloseReason())?mnSapIf007detail.getCloseReason():mnSapIf007detail.getExt1());
                    allocateApplyOrderDetailCreateDTO.setIsClosed(!org.apache.commons.lang3.StringUtils.isAllBlank(mnSapIf007detail.getExt1(),mnSapIf007detail.getCloseReason()) ? 1 : 0);
//                    allocateApplyOrderDetailCreateDTO.setIsClosed(Objects.nonNull(mnSapIf007detail.getCloseReason()) ? 1 : 0);
//            //行备注
                    allocateApplyOrderDetailCreateDTO.setRemark(mnSapIf007detail.getRemarks());
                    //扩展信息
//            allocateApplyOrderDetail.setFeatures(null,mnSapIf007detail.getFeatures());
                    allocateApplyOrderDetails.add(allocateApplyOrderDetailCreateDTO);
                }

                allocateApplyOrderUpdateDTO.setList(allocateApplyOrderDetails);
                //更新预调拨单数据
                Result<Boolean> updateAllocateApplyOrder = allocateApplyOrderWriteService.sapUpdateAllocateApplyOrder(allocateApplyOrderUpdateDTO);
                if (Objects.isNull(updateAllocateApplyOrder)) {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("更新预报单失败，返回值为空！");
                    saveSapRetry(mnSapIf007Request,"更新预报单失败，返回值为空！");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    return mnSapCommResponse;
                }
                if (Objects.isNull(updateAllocateApplyOrder.getResult())||!updateAllocateApplyOrder.getResult()) {
                    MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                    mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
                    mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                    mnSapCommSDO.setMessage("更新预报单失败");
                    mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
                    saveSapRetry(mnSapIf007Request,"更新预报单失败");
                    return mnSapCommResponse;
                }
            }
            //判断返回值是成功还是失败，失败给提示。
            //@TODO 这个字段有问题 后面改
            MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
            mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
            mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
            mnSapCommSDO.setExtId(mnSapIf007SDO.getAllocateApplyOrderId());
            List<MnSapCommDetail> mnSapCommDetails = new ArrayList<>();
            for (MnSapIf007detail mnSapIf007detail : mnSapIf007details) {
                MnSapCommDetail mnSapCommDetail = new MnSapCommDetail();
                mnSapCommDetail.setItemKey(mnSapIf007detail.getItem_key());
                mnSapCommDetail.setStatus(MnSAPStatus.SUCCESS.getCode());
                mnSapCommDetails.add(mnSapCommDetail);
            }
            mnSapCommSDO.setItem(mnSapCommDetails);
            mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
            //如果校验时间戳戳 这里记录时间戳
            if (checkTimestamp){
                cache(mnSapIf007SDO.getOutAllocateApplyOrderId(),mnSapIf007SDO.getFeatures());
            }
            return mnSapCommResponse;
        } catch (Exception e) {
            log.error("007.externalSyncUpdateAllocateApplyOrder.error,requeset:{}, Exception:{}", JSONObject.toJSONString(mnSapIf007Request), e);
            MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
            mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
            mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
            mnSapCommSDO.setMessage("007接口同步失败");
            mnSapCommResponse.setData(Lists.newArrayList(mnSapCommSDO));
            saveSapRetry(mnSapIf007Request,"007接口同步失败");
            return success(mnSapIf007Request);
        }
    }

    public  String getOrgCode(String orgId){
        //发货收货仓的组织id name
        BaselineGetOrganizationByIdsRequest r = new BaselineGetOrganizationByIdsRequest();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(orgId)){
            r.setIds(Lists.newArrayList(orgId));
            Object obj = baseDataService.baselineGetOrganizationByIds(r);
            JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(obj));
            if (o != null){
                JSONArray array = o.getJSONArray("result");
                if (array != null && array.size() > 0){
                    JSONObject j = array.getJSONObject(0).getJSONObject("organizationSDO");
                    if (j != null){
                        return j.getString("code");
                    }
                }
            }
        }
        return null;
    }
    public  String getOrgOutCodeBySoldPartCode(String soldPartCode){
        if (StringUtils.isBlank(soldPartCode)){
            return null;
        }
        BaselineGetOrganizationByCodes2Request baselineGetOrganizationByCodes2Request = new BaselineGetOrganizationByCodes2Request();
        baselineGetOrganizationByCodes2Request.setIds(Lists.newArrayList(soldPartCode));
        BaselineGetOrganizationByCodes2Response baselineGetOrganizationByCodes2Response = baseDataService.baselineGetOrganizationByCodes2(baselineGetOrganizationByCodes2Request);
        if (Objects.nonNull(baselineGetOrganizationByCodes2Response)&&CollectionUtils.isNotEmpty(baselineGetOrganizationByCodes2Response.getResult())){
            String outcode = baselineGetOrganizationByCodes2Response.getResult().get(0).getId();
            if (StringUtils.isNotBlank(outcode)){
                return outcode;
            }
        }
        return "6000";
    }


    public static MnSapCommResponse success(MnSapIf007Request request){
        MnSapCommResponse response = new MnSapCommResponse();
        MessageHeaderSDO messageHeaderSDO = request.getMessageHeader();
        if (request.getData() != null){
            List<MnSapCommSDO> mnSapCommSDOS = Lists.newArrayList();
            MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
            MnSapIf007SDO mnSapIf007SDO = request.getData();
            mnSapCommSDO.setHeaderKey(mnSapIf007SDO.getHeaderKey());
            mnSapCommSDO.setExtId(null);
            mnSapCommSDO.setMessage(MnSAPStatus.SUCCESS.getMsg());
            mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
            List<MnSapCommDetail> mnSapCommDetails = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(mnSapIf007SDO.getItems())) {
                mnSapCommDetails = mnSapIf007SDO.getItems().stream().map(m -> {
                    MnSapCommDetail mnSapCommDetail = new MnSapCommDetail();
                    mnSapCommDetail.setItemKey(m.getItem_key());
                    mnSapCommDetail.setStatus(MnSAPStatus.SUCCESS.getCode());
                    mnSapCommDetail.setMessage(MnSAPStatus.SUCCESS.getMsg());
                    return mnSapCommDetail;
                }).collect(Collectors.toList());
                mnSapCommSDO.setItem(mnSapCommDetails);
            }
            mnSapCommSDOS.add(mnSapCommSDO);
            response.setData(mnSapCommSDOS);
        }
        if (Objects.nonNull(messageHeaderSDO)) {
            response.setInterfacePath(messageHeaderSDO.getInterfacePath());
            response.setMessageId(messageHeaderSDO.getMessageId());
        }
        return response;
    }

    OrganizationSDO getOrgSDO(String orgId){
        if (StringUtils.isBlank(orgId)){
            return null;
        }
//        GetOrganiztionByIdRequest getOrganiztionByIdRequest = new GetOrganiztionByIdRequest();
//        getOrganiztionByIdRequest.setId(orgId);
//        OrganizationSDO organiztionById = otsPlatformEnhanceService.getOrganiztionById(getOrganiztionByIdRequest);
        BaselineGetOrganizationById2Request request = new BaselineGetOrganizationById2Request();
        request.setId(orgId);
        Result<OrganizationSDO> organizationSDOResult = baseDataService.baselineGetOrganizationById2(request);
        if (organizationSDOResult != null){
            return organizationSDOResult.getResult();
        }
        return null;
    }
    /**
     * 保存sap重试记录
     *
     */
    public void saveSapRetry(MnSapIf007Request request, String message){
        try{
            if (request == null || org.apache.commons.lang3.StringUtils.isBlank(message)){
                return;
            }
            MnSapIf007SDO sdo = request.getData();
            SapRetrySaveRequest sapRetrySaveRequest = new SapRetrySaveRequest();
            String requestJson = JSON.toJSONString(request);
            sapRetrySaveRequest.setParam(requestJson);
            sapRetrySaveRequest.setMsg(message);
            sapRetrySaveRequest.setMessageId(request.getMessageHeader().getMessageId());
            //请求时间戳
            sapRetrySaveRequest.setRequestTime(sdo.getFeatures());
            sapRetrySaveRequest.setApiCode(SapApiCode.SAP007.getValue());
            sapRetrySaveRequest.setOutKey(sdo.getOutAllocateApplyOrderId());
            sapRetrySaveRequest.setStatus(RetryStatus.FAIL.getValue());
            sapRetryWriteService.save(sapRetrySaveRequest);
        }catch (Throwable e){
            log.error("sapRetrySaveError",e);
        }
    }

    boolean checkModifierTime(MnSapIf007SDO sdo){
        String modifierTime = epochCacheService.get(BcOtsConstants.REDIS_CACHE_CODE(),
                FORECAST_ORDER_CACHE_KEY + sdo.getOutAllocateApplyOrderId());
        String ext = sdo.getFeatures();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(modifierTime)) {
            String[] modifierTimeArray = modifierTime.split("\\.");
            String[] extArray = ext.split("\\.");
            if (Long.parseLong(modifierTimeArray[0]) > Long.parseLong(extArray[0])) {
                return false;
            } else if (Long.valueOf(modifierTimeArray[0]).longValue() == Long.valueOf(extArray[0]).longValue()) {
                if (Long.parseLong(modifierTimeArray[1]) >= Integer.valueOf(extArray[1]).longValue()) {
                    return false;
                }
            }
        }
        return true;
    }
    void cache(String key,String time){
        if (org.apache.commons.lang3.StringUtils.isAnyBlank(key,time)){
            return;
        }
        epochCacheService.put(BcOtsConstants.REDIS_CACHE_CODE(),
                FORECAST_ORDER_CACHE_KEY + key,time,
                SAP_TIMESTAMP_CACHE_EXPIRE,
                TimeUnit.SECONDS);
    }
}
